<template>
  <div>
    <div>
      <el-upload
        :before-upload="beforeUpload"
        :on-change="onChange"
        :on-preview="onPreview"
        :on-remove="onRemove"
        :http-request="upload"
        :class="{ disabled: fileList.length > 0 }"
        list-type="picture-card"
        :file-list="fileList"
        action="#"
      >
        <i class="el-icon-plus" />
      </el-upload>
      <el-progress
        v-if="percenShow"
        style="width: 146px"
        :text-inside="true"
        :stroke-width="26"
        :percentage="percenNum"
      />
      <el-dialog
        class="uploadImage"
        :visible="showDialog"
        @close="showDialog = false"
      >
        <img :src="urlPath" alt="">
      </el-dialog>
    </div>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDIQHrCG4cvxhAMIxLSJtCEzUjhOp0uYw3',
  SecretKey: 'rRloa5IFvLVP2OTIp79uObXCbjcGelbB'
})
export default {
  data() {
    return {
      fileList: [],
      percenNum: 0,
      percenShow: false,
      showDialog: false,
      urlPath: ''
    }
  },
  methods: {
    onPreview(file) {
      this.showDialog = true
      this.urlPath = file.url
    },
    onRemove(file, newfileList) {
      this.fileList = newfileList
    },
    onChange(file, newfileList) {
      this.fileList = newfileList
    },
    beforeUpload(file) {
      const fileSize = 2 * 1024 * 1024
      // 上传前的大小限制
      if (file.size > fileSize) {
        this.$message.warning('上传大小只支持2M以下')
        return false
      }
      const typeAllowd = ['image/jpeg', 'image/png']
      // 上传前的类型限制
      if (!typeAllowd.includes(file.type)) {
        this.$message.warning('只支持 jpeg / png，这两种类型')
        return false
      }
    },
    upload(params) {
      this.percenShow = true
      cos.putObject(
        {
          Bucket: 'hr67-1307767593' /* 必须 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: params.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: params.file, // 上传文件对象
          onProgress: (progressData) => {
            console.log(progressData)
            // console.log(JSON.stringify(progressData))
            this.percenNum = progressData.percent * 100
          }
        },
        (err, data) => {
          if (!err) {
            this.fileList[0].url = 'http://' + data.Location
            this.fileList[0].status = 'success'
          }
          setTimeout(() => {
            this.percenShow = false
          }, 1000)
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
.uploadImage {
  img {
    max-width: 100%;
  }
}
</style>
